package com.example.datastorelearn

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

class MainActivity : AppCompatActivity() {

    private val mMainViewModel by lazy {
        ViewModelProvider(this)[MainViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val nameEt = findViewById<AppCompatEditText>(R.id.et_name)
        val ageEt = findViewById<AppCompatEditText>(R.id.et_age)
        val infoTv = findViewById<AppCompatTextView>(R.id.tv_info)

        findViewById<AppCompatButton>(R.id.btn_save).setOnClickListener {
//            runBlocking {
//                mMainViewModel.save(nameEt.text.toString(), ageEt.text.toString().toInt())
//            }
            lifecycleScope.launch {
                mMainViewModel.save(nameEt.text.toString(), ageEt.text.toString().toInt())
            }
        }

        findViewById<AppCompatButton>(R.id.btn_load).setOnClickListener {
            runBlocking {
                val info = mMainViewModel.load().first()
                infoTv.setText("name = ${info.name} age = ${info.age}")
            }
        }
    }
}